import React, { useContext, FunctionComponentElement, useState } from "react";
import classNames from "classnames";
import { MenuContext } from "./menu";
import { MenuProps } from "./menu";
import { Icon } from "../Icon/Icon";
import { MenuItemProps } from "./menuItem";
export interface SubMenuProps {
  index?: string;
  title: string;
  className?: string;
  children?: React.ReactNode;
}

export const SubMenu: React.FC<SubMenuProps> = (props) => {
  const { index, title, className, children } = props;
  const context = useContext(MenuContext);
  const openedSubMenus = context.defaultOpenSubMenus as Array<string>;
  const isOpend =
    index && context.mode === "vertical"
      ? openedSubMenus.includes(index)
      : false;

  const [open, setopen] = useState(isOpend);
  const classes = classNames("menu-item submenu-item", className, {
    "is-active": context.index === index,
    "is-opend": open,
    "is-vertical": context.mode === "vertical",
  });
  const handleClick = (e: React.MouseEvent) => {
    e.preventDefault();
    setopen(!open);
  };

  let timer: any;
  const handleMouse = (e: React.MouseEvent, toggle: boolean) => {
    clearTimeout(timer);
    e.preventDefault();
    timer = setTimeout(() => {
      setopen(toggle);
    }, 30);
  };
  const clickEvents =
    context.mode === "vertical"
      ? {
          onClick: handleClick,
        }
      : {};
  const hoverEvents =
    context.mode !== "vertical"
      ? {
          onMouseEnter: (e: React.MouseEvent) => {
            handleMouse(e, true);
          },
          onMouseLeave: (e: React.MouseEvent) => {
            handleMouse(e, false);
          },
        }
      : {};
  const rederChildren = () => {
    const subMenuClasses = classNames("coerger-submenu", {
      "menu-opened": open,
    });
    const childrenComponent = React.Children.map(children, (child, i) => {
      const childElement = child as FunctionComponentElement<MenuItemProps>;
      if (childElement.type.displayName === "MenuItem") {
        return React.cloneElement(childElement, { index: `${index}-${i}` });
      } else {
        console.error("Waring:Menu has a child which is not a MenuItem");
      }
    });
    return <ul className={subMenuClasses}>{childrenComponent}</ul>;
  };
  return (
    <li key={index} className={classes} {...hoverEvents}>
      {/* <>
      //最开始这样写，虽然不报错了，但是特别卡
        <div className="submenu-title" onClick={handleClick} {...clickEvents}>
          {title}
          {rederChildren()}
        </div>
      </> */}
      <div className="submenu-title" onClick={handleClick} {...clickEvents}>
        <div>
          {title}
          <Icon icon="angle-down" className="arrow-icon"></Icon>
        </div>

        {rederChildren()}
      </div>
    </li>
  );
};
SubMenu.displayName = "SubMenu";
export default SubMenu;
